<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Trans\Refunds\RefundsService;
use JLPay\Models\Trans\Refunds\RefundsRequest;
use JLPay\Models\Trans\Refunds\RefundsResponse;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 交易 - 退款申请功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

/**
 * 构建退款申请请求
 */
function buildRefundsRequest(): RefundsRequest
{
    $request = new RefundsRequest();
    
    // 设置请求参数
    $request->setMchId("849584358120018")
        ->setOutTradeNo("20250318500005Test")
        ->setOriOutTradeNo("20250318100005Test")
        //->setOriTransactionId("80011557201909171853011568")
        ->setTotalFee("1")
        ->setRemark("测试退款申请")
        ->setMchCreateIp("127.0.0.1")
        ->setLongitude("116.397128")
        ->setLatitude("39.916527")
        ->setNotifyUrl("http://172.20.20.85:38001/jlpay/refunds/notify");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 退款申请示例
 */
function refundsDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行退款申请示例");
    
    // 创建配置对象和退款服务
    $config = createConfig();
    $refundsService = new RefundsService($config);
    
    // 创建退款申请请求
    $request = buildRefundsRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $refundsService, 
        $request, 
        "退款申请",
        function($service, $request) {
            return $service->refunds($request);
        }
    );
    
    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    
    $logger->info("退款申请示例执行完毕");
}

// =================== 主程序 =====================
$logger = Logger::getInstance();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 退款申请示例 开始 =====");
$logger->info("=" . str_repeat("=", 50));

refundsDemo();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 退款申请示例执行完毕 =====");
$logger->info("=" . str_repeat("=", 50)); 